<template>
    <div class="center" v-loading="loading">
        <basic-infor-mation ref="basicInform"
         @basicInformChange="basicInformChange" 
         @userTypeChange="userTypeChange"
         :regionList="regionList"
         :secondaryList="secondaryList"
         :basicInformEdit = "basicInformEdit"
         :walletId="walletId"
         /> 
        <settlement-config :settleConfigEdit="settleConfigEdit" ref="settlement" @settlementChange="settlementChange"/>
        <cash-out-config :qry_cash_config_list="qry_cash_config_list" ref="cashOut" @cashOutConfigChange="cashOutConfigChange"/>
        <img-qualifi-cation  :editFileList="basicInformEdit.file_list" ref="imgQualifi" @fileListChange="fileListChange" :merchantId="merchantId" :userType="userType"/>
        <el-card class="submit">
          <el-button icon="el-icon-check" :loading="btnLoading" type="primary" @click="submit">提交</el-button>
        </el-card>
    </div>
</template>

<script>
 import basicInformation from "./components/basicInformation.vue"
 import settlementConfig from "./components/settlementConfig.vue"
 import cashOutConfig from "./components/cashOutConfig.vue"
 import imgQualification from "./components/imgQualification.vue"
 import { busimodify , basicdataEntModify , basicdataUpdata , basicdataIndv , huifuUserUusiOpen ,getAreaAll , basicdataQuery , basicdataEnt} from '@/api/fetchApi.js'
 export default{
    data(){
      return{
        loading:false,
        btnLoading:false,
        regionList:[],
        merchantId:'',
        userType:'1',
        file_list:[],
        basicInform:{},
        reqData:{
          req_seq_id:"",
          req_date:''
        },
        walletId:'',
        upper_huifu_id:'',
        cash_config:[],
        settle_config:{},
        basicInformEdit:{}, //个人用户基本信息
        qry_cash_config_list:[], // 取现配置列表
      }
    },
    components:{
        'basic-infor-mation':basicInformation,
        'settlement-config':settlementConfig,
        'cash-out-config':cashOutConfig,
        'img-qualifi-cation':imgQualification
    },
    mounted(){
       this.initMerchantInfo()
       this.initApiData()
       this.initArealist()
       this.walletId = 0
       if(this.$route.query.mid){
         this.initDetail(this.$route.query.mid)
       }
    },
    methods:{
     async initDetail(mid){
        this.loading = true
        const res = await basicdataQuery({merchantId:mid})
          this.basicInformEdit = Object.assign({},res.data.qry_cash_card_info_list ? JSON.parse(res.data.qry_cash_card_info_list)[0] : {} , res.data.indv_base_info? JSON.parse(res.data.indv_base_info) : JSON.parse(res.data.ent_base_info))
          this.qry_cash_config_list = res.data.qry_cash_config_list ? JSON.parse(res.data.qry_cash_config_list) : []
          this.settleConfigEdit = res.data.settle_config ? JSON.parse(res.data.settle_config) : {}
          this.walletId = res.data.wallet ? res.data.wallet.id : 11
          this.upper_huifu_id = res.data.upper_huifu_id
          this.huifu_id = res.data.wallet ? res.data.wallet.channelAcctNo : this.$route.query.huifu_id
          this.basicInformEdit.file_list.forEach(item=>{
            res.data.file_list.forEach(imgList=>{
               if(item.file_type == imgList.file_type){
                  item.file_url = imgList.file_url
               }
            })
          })
        this.loading = false
      },
      initMerchantInfo(){
        if(this.$route.query.mid){
          this.merchantId = this.$route.query.mid
        }else{
          const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
          this.merchantId = userInfo.mid
        }
      },
      basicInformChange(v){
        this.basicInform = v
      },
      settlementChange(v){
        this.settle_config = v
      },
      cashOutConfigChange(v){
        this.cash_config = []
        if(v.T1Form.cash_type){
          this.cash_config.push(v.T1Form)
        }
         if(v.DMForm.cash_type){
          this.cash_config.push(v.DMForm)
        }
      },
      userTypeChange(v){
       this.userType = v
      },
      fileListChange(v){
        this.file_list = v
      },
      initApiData(){
        const now = new Date();
	      const year = now.getFullYear();
	      const month = (now.getMonth() + 1) < 10 ? '0' + (now.getMonth() + 1) : now.getMonth() 
	      const day = now.getDate() < 10 ? '0' + now.getDate() : now.getDate()
        this.reqData.req_seq_id  = now.getTime()
        this.reqData.req_date  = year + '' + month + '' + day
      },
      async submit(){
       const formValid = await  Promise.all([this.$refs.imgQualifi.$refs.formRules.validate(),  this.$refs.basicInform.$refs.formRules.validate(),this.$refs.settlement.$refs.formRules && this.$refs.settlement.$refs.formRules.validate(),this.$refs.cashOut.$refs.formRules && this.$refs.cashOut.$refs.formRules.validate()])
       if(!formValid) return
       this.btnLoading = true
       if(this.userType == 1){
          this.personalOpen() //个人
       }else{
          this.enterpriseOpen() // 企业
       }
      },
      async enterpriseOpen(){
        this.initApiData()
        setTimeout(async()=>{
        const data = Object.assign({},{file_list:this.file_list},this.basicInform,this.reqData)
        if(this.walletId){
          data.huifu_id = this.huifu_id
          // console.log(console.log(data))
          let res = await basicdataEntModify({merchantId:this.merchantId , data:JSON.stringify(data)})
          if(res.code == 200){
           this.btnLoading = false
           this.configCardInfo(res.data)
          }else{
            this.btnLoading = false
          this.$message.error(res.message)
          }
        }else{
          let res = await basicdataEnt({merchantId:this.merchantId , data:JSON.stringify(data)})
          if(res.code == 200){
            this.btnLoading = false
            this.walletId = res.data.walletId // 注意这里，作用是如果业务入驻报错了，是用来走编辑操作的
            this.huifu_id = res.data.huifu_id // 注意这里，作用是如果业务入驻报错了，是用来走编辑操作的
            this.merchantId = res.data.merchantId
            this.upper_huifu_id = res.data.upper_huifu_id
           this.configCardInfo(res.data)
          }else{
            this.btnLoading = false
           this.$message.error(res.message)
          }
        }
       })
      },
      async personalOpen(){
        this.initApiData()
       setTimeout(async()=>{
        const data = Object.assign({},{file_list:this.file_list},this.basicInform,this.reqData)
        if(this.walletId){
          data.huifu_id = this.huifu_id
          let res = await basicdataUpdata({merchantId:this.merchantId , data:JSON.stringify(data)})
          if(res.code == 200){
            this.btnLoading = false
           this.configCardInfo(res.data)
        }else{
          this.btnLoading = false
          this.$message.error(res.message)
        }
        }else{
          let res = await basicdataIndv({merchantId:this.merchantId , data:JSON.stringify(data)})
          if(res.code == 200){
            this.btnLoading = false
            this.walletId = res.data.walletId  // 注意这里，作用是如果业务入驻报错了，是用来走编辑操作的
            this.huifu_id = res.data.huifu_id // 注意这里，作用是如果业务入驻报错了，是用来走编辑操作的
            this.merchantId = res.data.merchantId // 注意这里，作用是如果业务入驻报错了，是用来走编辑操作的
            this.upper_huifu_id = res.data.upper_huifu_id // 注意这里，作用是如果业务入驻报错了，是用来走编辑操作的
            this.configCardInfo(res.data)
        }else{
          this.btnLoading = false
          this.$message.error(res.message)
        }
        }
       })
      },
      async  configCardInfo(v){
        this.btnLoading = true
        this.initApiData()
        setTimeout(async()=>{
          const card_info = {
            card_type:this.basicInform.card_type, 
            card_name:this.basicInform.card_name,
            bank_code:this.basicInform.bank_code,
            card_no:this.basicInform.card_no,
            prov_id:this.basicInform.prov_id,
            area_id:this.basicInform.area_id,
            branch_code:this.basicInform.branch_code
          }
          const data = Object.assign({},this.reqData,{card_info},{huifu_id:v.huifu_id || this.huifu_id ,upper_huifu_id:v.upper_huifu_id || this.upper_huifu_id},{cash_config:this.cash_config}, this.settle_config.settle_cycle ?{settle_config:this.settle_config} : {})
          if(this.walletId){  //有钱包编辑
            // console.log(JSON.stringify({merchantId:this.merchantId,data:JSON.stringify(data)}))
           if(this.qry_cash_config_list.length == 0){ //一个都没有，新增
             if(this.cash_config.length){ //是否有提现方式要新增
              const addData = Object.assign({},this.reqData,{card_info},{huifu_id:v.huifu_id || this.huifu_id ,upper_huifu_id:v.upper_huifu_id || this.upper_huifu_id},{cash_config:this.cash_config})
              const addRes = await huifuUserUusiOpen({merchantId:this.merchantId,data:JSON.stringify(addData)})
              if(addRes.code == 200){
                   this.btnLoading = false
                   this.$message.success('提交成功！')
                   const res = await busimodify({merchantId:this.merchantId,data:JSON.stringify(data)})
                 if(res.code == 200){
                   this.btnLoading = false
                   this.$router.back()
                   this.$message.success('提交成功！')
                   this.$router.back()
                 }else{
                   this.btnLoading = false
                   this.$message.error(res.message)
                 }
               }else{
                   this.btnLoading = false
                   this.$message.error(addRes.message)
               }
             }else{
              const res = await busimodify({merchantId:this.merchantId,data:JSON.stringify(data)})
                 if(res.code == 200){
                  this.$router.back()
                   this.btnLoading = false
                   this.$message.success('提交成功！')
                 }else{
                   this.btnLoading = false
                   this.$message.error(res.message)
                 }
             }
            
           }else if(this.qry_cash_config_list.length == 2){ //全部都有，编辑
               const res = await busimodify({merchantId:this.merchantId,data:JSON.stringify(data)})
               if(res.code == 200){
                 this.btnLoading = false
                 this.$router.back()
                 this.$message.success('修改成功！')
               }else{
                 this.btnLoading = false
                 this.$message.error(res.message)
               }
           }else if(this.qry_cash_config_list.length == 1){ // 有一个，可能编辑 可能新增
              let addArr = []
              this.cash_config.forEach(item=>{
                if(this.qry_cash_config_list[0].cash_type != item.cash_type){
                  addArr.push(item)
                }
                
              })
              if(addArr.length){
                const addData = Object.assign({},this.reqData,{card_info},{huifu_id:v.huifu_id || this.huifu_id ,upper_huifu_id:v.upper_huifu_id || this.upper_huifu_id},{cash_config:addArr})
              const addRes = await huifuUserUusiOpen({merchantId:this.merchantId,data:JSON.stringify(addData)})
              if(addRes.code == 200){
                   this.btnLoading = false
                   this.$message.success('提交成功！')
                   const res = await busimodify({merchantId:this.merchantId,data:JSON.stringify(data)})
                 if(res.code == 200){
                  this.$router.back()
                   this.btnLoading = false
                   this.$message.success('提交成功！')
                 }else{
                   this.btnLoading = false
                   this.$message.error(res.message)
                 }
               }else{
                   this.btnLoading = false
                   this.$message.error(addRes.message)
               }
              }else{
                const res = await busimodify({merchantId:this.merchantId,data:JSON.stringify(data)})
                 if(res.code == 200){
                   this.btnLoading = false
                  this.$router.back()
                   this.$message.success('提交成功！')
                 }else{
                   this.btnLoading = false
                   this.$message.error(res.message)
                 }
              }
           }
          }else{ //无钱包，新增
            const res = await huifuUserUusiOpen({merchantId:v.merchantId,data:JSON.stringify(data)})
          if(res.code == 200){
            this.$router.back()
            this.btnLoading = false
            this.$message.success('创建成功！');
          }else{
            this.btnLoading = false
            this.$message.error(res.message);
          }
          }
        },100)
      },
      async initArealist(){
           const res = await getAreaAll()
           this.secondaryList = JSON.parse(JSON.stringify(res.data))
           res.data.forEach(item=>{
            item.children.forEach(chItem=>{
              chItem.children = ''
            })
           })
           this.regionList = res.data
        },
    }
 }
</script>



<style scoped>

.center{
    width: calc(100% - 36px );
    height: calc(100% - 36px );
    overflow-y:auto;
    background-color: #fff;
    border-radius: 4px;
    padding: 18px;
    margin: auto;
    /* padding-top: 30px; */
}
.center-form{
  padding: 0 22px;
}
.center-construct{
    width: 100%;
    display: flex;
    justify-content: end;
    margin-bottom: 30px;
}
.center-table{
    margin-top: 30px;
    padding: 0 20px;
}
.construct-dialog{
    height: 60vh;
    overflow-y: auto;
}
::v-deep .el-upload--text{
    width: 160px;
    height: 160px;
    line-height: 160px;
}
.video{
  width: 160px;
    height: 160px;
}
/* 针对 Firefox */
.center {
  scrollbar-width: none; /* Firefox */
}
 
/* 针对 Chrome, Edge 和 Safari */
.center::-webkit-scrollbar {
  width: 0; /* Chrome, Edge 和 Safari */
}
 
/* 针对 IE 10+ */
.center {
  -ms-overflow-style: none;  /* IE 10+ */
}
 
/* 针对 IE 11 */
.center {
  overflow: auto;
}

.avatar{
  width: 160px;
  height: 160px;
}

.submit{
  display:flex;
  justify-content:center;
}
</style>